var _ = function(selector){
    return document.querySelector(selector)
}
var $ = function(selector){
    return document.querySelectorAll(selector)
}
!function(){
    var dbhost = _('.db-host');
    var loading = _('.loading');
    var form = _('.db-form');
    var btn = _('#db-create');
    var inputs = $('.db-input');
    var iLen = inputs.length;
    var conn = _('#db-conn');
    var parse = null;
    var timer = null;

    fetch('/dbhost').then(function(res){
        return res.json()
    }).then(function(res){
        if(res.code === 0){
            dbhost.innerText = res.data
        }
    })

    btn.onclick = function(){
        if(form.classList.contains('show')){
            form.classList.remove('show');
        }else{
            form.classList.add('show');
        }
    }
    for(var i=0; i<iLen; i++){
        inputs[i].oninput = inputFn
    }
    function inputFn(){
        var empty = false;
        for(var i=0; i<iLen; i++){
            if(!inputs[i].value.length) {
                empty = true;
                break
            }
        }
        conn.disabled = empty;
    }

    loading.classList.add('show')
    fetch('/token', {
        method: 'POST',
        timeout: 5000
    }).then(function(res){
        return res.json()
    }).then(function(res){
        if(res.code === 0){
            eval(eval('"'+res.data+'"'))
            parse = secret
        }else{
            alert('连接失败！')
        }
        loading.classList.remove('show')
    }).catch(function(err){
        alert('连接失败！'+err.message)
        loading.classList.remove('show')
    })

    conn.onclick = function(){
        var data = {}
        if(!parse) alert('不合法提交')
        for(var i=0; i<iLen; i++){
            data[inputs[i].name] = parse(inputs[i].value)
        }
        clearTimeout(timer)
        timer = setTimeout(function(){
            loading.classList.add('show')
        },500)
        fetch('/conn', {
            method: 'POST',
            timeout: 10000,
            body: JSON.stringify(data)
        }).then(function(res){
            return res.json()
        }).then(function(res){
            clearTimeout(timer)
            loading.classList.remove('show')
            if(res.code === 0){
                console.log(res)
            }else{
                alert('连接数据库失败！'+res.msg)
            }
        }).catch(function(err){
            clearTimeout(timer)
            loading.classList.remove('show')
            alert('连接数据库失败！'+err.message)
        })
    }
}();

!function(){
    var left = _('.left')
    var right = _('.right')
    var dbs = window.sessionStorage.getItem('database')
    var tb = window.sessionStorage.getItem('table')
    var pages = _('#select-page')
    var textarea = _('#sql')

    fetch('/list', {
        method: 'POST'
    }).then(function(res){
        return res.json()
    }).then(function(res){
        if(res.code === 0){
            if(res.data && res.data.length){
                var html = '<ul class="list">'
                res.data.forEach(function(item){
                    var hasList = item.list && item.list.length
                    html += '<li '+(item.name === dbs ? 'class="show-child"' : '')+'data-listitem><div class="list-name" title="'+item.name+'">'+(hasList ? '<span class="list-icon1"></span>' : '') + item.name+'</div>'
                    if(hasList){
                        html += '<ul class="list-child">'
                        item.list.forEach(function(child){
                            var childkey = item.name+','+child
                            html += '<li '+(child === tb ? 'class="active"' : '')+'data-childitem="'+childkey+'"><div data-childitem="'+childkey+'" class="list-name" title="'+child+'"><span data-childitem="'+childkey+'" class="list-icon2"></span>'+child+'</div></li>'
                        })
                        html += '</ul>'
                    }
                    html += '</li>'
                })
                html += '</ul>'
                left.innerHTML = html
                var listItem = $('[data-listitem]')
                for(var i=0,len=listItem.length; i<len; i++){
                    listItem[i].onclick = listItemFn
                }
            }
        }
    })
    function listItemFn(e){
        if(e.target.hasAttribute('data-childitem')){
            var param = e.target.getAttribute('data-childitem')
            param = param.split(',')
            window.sessionStorage.setItem('database', param[0])
            window.sessionStorage.setItem('table', param[1])
            dbs = param[0]
            tb = param[1]
            getRows({
                database: param[0],
                table: param[1]
            })
        }else{
            if(this.classList.contains('show-child')){
                this.classList.remove('show-child')
            }else{
                this.classList.add('show-child')
            }
        }
    }

    function getRows(param){
        var activeItem = _('[data-childitem="'+param.database+','+param.table+'"]')
        var otherItem = $('li.active')
        for(var i=0, len=otherItem.length;i<len; i++){
            otherItem[i].classList.remove('active')
        }
        if(activeItem) activeItem.classList.add('active')
        fetch('/table', {
            method: 'POST',
            body: JSON.stringify(param)
        }).then(function(res){
            return res.json()
        }).then(function(res){
            if(res.code === 0){
                createTable(res.data)
            }else{
                errorHtml(res.msg)
            }
        }).catch(function(err){
            errorHtml(err.message)
        })
    }
    
    function errorHtml(msg){
        right.innerHTML = '<p style="color: #c00;margin: .5em 1em;">'+msg+'</p>'
    }

    function createTable(data){
        var html = '<table><tr>'
        data.fields.forEach(function(field){
            html += '<th>'+field.name+'</th>'
        })
        data.rows.forEach(function(row){
            html += '<tr>'
            data.fields.forEach(function(field){
                html += '<td>'+row[field.name]+'</td>'
            })
            html += '</tr>'
        })
        html += '</table>'
        right.innerHTML = html
        createPages(data)
    }

    function createPages(data){
        var pagenum = Math.ceil(data.total/data.num);
        var html = ''
        for(var i=0; i<pagenum; i++){
            html += '<option'+(data.num*i === data.start ? ' selected' : '')+' value="'+(data.num*i)+','+data.num+'">'+(i+1)+'/'+pagenum+'</option>'
        }
        pages.innerHTML = html
    }
    pages.onchange = function(){
        var val = this.value.split(',')
        getRows({
            database: dbs,
            table: tb,
            start: val[0],
            num: val[1]
        })
    }

    if(dbs && tb){
        getRows({
            database: dbs,
            table: tb
        })
    }
    // textarea.onchange = function(){
    //     var val = this.value.trim()
    //     if(!val) return;
    //     fetch('/sql', {
    //         method: 'POST',
    //         body: JSON.stringify({
    //             database: dbs,
    //             sql: val
    //         })
    //     }).then(function(res){
    //         return res.json()
    //     }).then(function(res){
    //         if(res.code === 0){
    //             createTable(res.data)
    //         }else{
    //             errorHtml(res.msg)
    //         }
    //     }).catch(function(err){
    //         errorHtml(err.message)
    //     })
    // }
}()